<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('pageSessions.table.setting')"
    width="500"
  >
    <el-form :model="form" :rules="rules">
      <el-form-item
        :label="$t('pageSessions.modal.sessionTimeout')"
        label-width="140px"
        prop="sessionTimeout"
      >
        <el-input
          class="w-48"
          v-model="form.SessionTimeout"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">
          {{ $t('global.action.cancel') }}
        </el-button>
        <el-button type="primary" @click="onOk">
          {{ $t('global.action.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useSessionsStore } from '@/store/UserSecurity/Sessions/SessionsStore';
import useVuelidateTool from '@/hooks/useVuelidateTool';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();
const { useVuelidate, required, numeric, elementInputValidator } =
  useVuelidateTool();
const sessionsStore = useSessionsStore();

const form = reactive({
  SessionTimeout: 0,
});

const v$ = useVuelidate(
  {
    SessionTimeout: {
      required,
      numeric,
    },
  },
  form,
);

const rules = computed(() => {
  return {
    sessionTimeout: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'sessionTimeout'),
      },
    ],
  };
});

const dialogVisible = ref(false);
defineExpose({ dialogVisible });

await sessionsStore.getSessionsData();
await sessionsStore.getSessionTimeout().then(() => {
  form.SessionTimeout = sessionsStore.sessionTimeout;
});

const onOk = () => {
  handleSubmit();
};
const closeModal = () => {
  nextTick(() => {
    dialogVisible.value = false;
  });
};
const resetForm = () => {
  form.SessionTimeout = sessionsStore.sessionTimeout;
  v$.value.$reset();
  closeModal();
};
const handleSubmit = async () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  form.SessionTimeout = +form.SessionTimeout;
  closeModal();
  sessionsStore
    .commitSessionSettings(form)
    .then(() => {
      ElNotification({
        type: 'success',
        message: i18n.t('pageSessions.table.settingSuccessfully'),
      });
    })
    .catch(() => {
      ElNotification({
        type: 'error',
        message: i18n.t('pageSessions.table.errorSetting'),
      });
    });
};
</script>
